package training03;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Training {
    public  Training(){
        process();
    }
    public List read(String fileName){
        FileReader reader = null;
        List list = new ArrayList();
        try {
            reader = new FileReader(fileName);
            BufferedReader bufferedReader = new BufferedReader(reader);
            String str = null;
            while((str = bufferedReader.readLine()) != null){
                String [] strs = str.split(" +");
                list.add(new Student(Integer.parseInt(strs[0]),strs[1],strs[2],strs[3]));
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally{
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return list;
    }
    public void process(){
        List<Student> list = read("student.txt");
        Map<String,List<Student>> map = new HashMap();
        for(Student stu  : list){
            if(map.containsKey(stu.getClassName())){
                map.get(stu.getClassName()).add(stu);
            }else{
                List newList = new ArrayList();
                newList.add(stu);
                map.put(stu.getClassName(),newList);
            }
        }
        for(String key : map.keySet()){
            write(map.get(key),key + ".txt");
        }

    }
    public void write(List<Student> list,String fileName){
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fileName);
            StringBuffer stringBuffer = new StringBuffer();
            for(Student stu : list){
                stringBuffer.append(stu.toString() + "\n");
            }
            fos.write(stringBuffer.toString().getBytes());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
    public static void main(String[] args) {
        new Training();
    }
}
